package io.capsulode.tunnel.blockrepo.proxydef;

import io.capsulode.tunnel.blockrepo.ProxyDefinition;
import io.capsulode.tunnel.blockrepo.ProxyRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * YamlFile
 *
 * @author lipei
 */
@Service
public class YamlFile implements ProxyRepository {
    private static final Logger logger = LoggerFactory.getLogger(YamlFile.class);
    private final File db = getStorage().toFile();

    private static Path getStorage() {
        Path dbPath = Paths.get("proxies.yaml");
        if (logger.isDebugEnabled()) {
            logger.debug("Use storage: {}", dbPath.toAbsolutePath());
        }
        return dbPath;
    }

    @Override
    public void put(ProxyDefinition proxy) {
        throw new UnsupportedOperationException("暂不支持的操作，请直接修改文件：" + db);
    }

    @Override
    public void remove(String proxyName) {
        throw new UnsupportedOperationException("暂不支持的操作，请直接修改文件：" + db);
    }

    @Override
    public String etag() {
        ByteBuffer buffer = ByteBuffer.allocate(Long.BYTES);
        buffer.putLong(lastModified());

        return DigestUtils.md5DigestAsHex(buffer.array());
    }

    @Override
    public long lastModified() {
        return db.lastModified();
    }

    @Override
    public void write(OutputStream out) throws IOException {
        if (db.exists()) {
            Files.copy(db.toPath(), out);
        }
    }

}